package com.example.yls.inote;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;

import com.example.yls.inote.data.DataStore;
import com.example.yls.inote.models.Note;

/**
 * Created by My Family on 2018/6/9.
 */

public class NoteEditActivity extends AppCompatActivity {
    private EditText titleEdt;
    private EditText bodyEdt;
    private long updatedTime;
    private boolean mIsAdd;
    private String mNoteContent;
    private int mPosition;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.edit_note);

        titleEdt = findViewById(R.id.edit_title);
        bodyEdt = findViewById(R.id.edit_body);

        mIsAdd = getIntent().getBooleanExtra("is_add", false);

        if(mIsAdd){
            updatedTime = System.currentTimeMillis();
            mNoteContent = "";
        }else {
            mPosition = getIntent().getIntExtra("position", 0);
            updatedTime = getIntent().getLongExtra("modified_time", 0);
            mNoteContent = getIntent().getStringExtra("note_content");
        }



    }



    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_accept, menu);
        return super.onCreateOptionsMenu(menu);

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case R.id.action_accept:
                save();
                finish();
                break;
            default:
                return super.onOptionsItemSelected(item);
        }
        return super.onOptionsItemSelected(item);

    }


    private void save() {
        DataStore.execute(new Runnable() {
            @Override
            public void run() {
                Note note = updateNote();
                DataStore.getNotes().insert(note);
            }
        });
    }

    private Note updateNote() {
        Note note = new Note();
        note.setTitle(titleEdt.getText().toString());
        note.setBody(bodyEdt.getText().toString());
        note.setCreatedAt(updatedTime);
        note.setUpdatedTime(updatedTime);

        return note;
    }
}

